const utils = require("../utils")
const dbModel = require('../models/dbModel')

let getUserData = async (ctx) => { // 分页查询
    try {
        const res = await dbModel.userDataModel.find({})
        const totle = await dbModel.userDataModel.count()
        ctx.body = utils.assembleData({
            res,
            totle
        })
    } catch (error) {
        ctx.body = error;
    }
};

let update = async (ctx) => { //新增
    try {
        let req = ctx.request.body;
        let {
            title,
            time,
            content,
            original,
            des
        } = req;
        // title  相同的为修改为过滤条件 // 第二个参数为过滤条件0为不需要
        let jsonkoa = await dbModel.authDataModel.update({
            title
        }, {
            $set: {
                title,
                time,
                content,
                original,
                des
            }
        }, {
            upsert: true
        });
        let {
            ok
        } = jsonkoa;
        ctx.body = {
            error: 0,
            success: ok
        }
    } catch (error) {
        //handle error
        ctx.body = error;
    }
};

let delectData = async (ctx) => {
    try {
        let req = ctx.request.query;
        let id = req.id;
        let data = await dbModel.authDataModel.remove({
            _id: id
        });
        let {
            n,
            ok
        } = data;
        ctx.body = {
            del: n,
            ok
        }
    } catch (error) {
        ctx.body = error;
    }
};

module.exports = {
    update,
    delectData,
    getUserData
}